/**
 * User Management Panel UI
 */

export function getUserManagementHTML() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Anthropic Proxy - User Management</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        [x-cloak] { display: none !important; }
        .user-card {
            transition: all 0.3s ease;
        }
        .user-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .spinner {
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100">
    <div x-data="userManager()" x-init="init()" x-cloak>
        <!-- Header -->
        <div class="bg-white shadow-sm border-b">
            <div class="container mx-auto px-4 py-4">
                <div class="flex justify-between items-center">
                    <div class="flex items-center space-x-4">
                        <h1 class="text-2xl font-bold text-gray-800">👥 User Management</h1>
                        <a href="/monitor" class="text-blue-500 hover:text-blue-700 flex items-center gap-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                            </svg>
                            Back to Monitor
                        </a>
                    </div>
                    <div class="flex gap-2">
                        <button @click="showAddUserModal()" 
                                class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 flex items-center gap-2">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                            </svg>
                            Add User
                        </button>
                        <button @click="loadUsers()"
                                class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 flex items-center gap-2">
                            <svg class="w-4 h-4 spinner" x-show="loading" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>
                            <svg class="w-4 h-4" x-show="!loading" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                            </svg>
                            Refresh
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <div x-show="alertMessage" 
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0 transform translate-y-2"
             x-transition:enter-end="opacity-100 transform translate-y-0"
             x-transition:leave="transition ease-in duration-200"
             x-transition:leave-start="opacity-100 transform translate-y-0"
             x-transition:leave-end="opacity-0 transform translate-y-2"
             class="container mx-auto px-4 mt-4">
            <div :class="alertType === 'success' ? 'bg-green-100 border-green-400 text-green-700' : 'bg-red-100 border-red-400 text-red-700'"
                 class="border px-4 py-3 rounded relative" role="alert">
                <span class="block sm:inline" x-text="alertMessage"></span>
                <span @click="alertMessage = ''" class="absolute top-0 bottom-0 right-0 px-4 py-3 cursor-pointer">
                    <svg class="fill-current h-6 w-6" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                        <title>Close</title>
                        <path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/>
                    </svg>
                </span>
            </div>
        </div>

        <!-- Main Content -->
        <div class="container mx-auto px-4 py-6">
            <!-- Status Overview -->
            <div class="bg-white rounded-lg shadow p-6 mb-6">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="text-center">
                        <div class="text-3xl font-bold" :class="authStatus.enabled ? 'text-green-600' : 'text-gray-400'">
                            <span x-text="authStatus.enabled ? '✅' : '❌'"></span>
                        </div>
                        <div class="text-sm text-gray-600 mt-1">Authentication Status</div>
                        <div class="font-semibold" x-text="authStatus.enabled ? 'Enabled' : 'Disabled'"></div>
                    </div>
                    <div class="text-center">
                        <div class="text-3xl font-bold text-blue-600" x-text="users.length"></div>
                        <div class="text-sm text-gray-600 mt-1">Total Users</div>
                    </div>
                    <div class="text-center">
                        <div class="text-3xl font-bold text-purple-600">🔐</div>
                        <div class="text-sm text-gray-600 mt-1">Security Mode</div>
                        <div class="font-semibold">User Token Auth</div>
                    </div>
                </div>
            </div>

            <!-- Users List -->
            <div class="bg-white rounded-lg shadow">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h2 class="text-lg font-semibold text-gray-800">User List</h2>
                </div>
                
                <div class="p-6">
                    <div x-show="loading" class="text-center py-8">
                        <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                        <p class="mt-2 text-gray-600">Loading users...</p>
                    </div>

                    <div x-show="!loading && users.length === 0" class="text-center py-8">
                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                        <p class="mt-2 text-gray-600">No users configured</p>
                        <p class="text-sm text-gray-500 mt-1">Add your first user to enable authentication</p>
                    </div>

                    <div x-show="!loading && users.length > 0" class="grid gap-4">
                        <template x-for="(user, index) in users" :key="index">
                            <div class="user-card bg-gray-50 rounded-lg p-4 border border-gray-200">
                                <div class="flex justify-between items-center">
                                    <div class="flex-1">
                                        <div class="flex items-center gap-2">
                                            <span class="text-lg font-semibold text-gray-800" x-text="user.name"></span>
                                            <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">
                                                User #<span x-text="index + 1"></span>
                                            </span>
                                        </div>
                                        <div class="mt-2 flex items-center gap-2 text-sm text-gray-600">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"></path>
                                            </svg>
                                            <code class="bg-gray-200 px-2 py-1 rounded font-mono text-xs">
                                                <span x-text="user.token ? user.token.substring(0, 20) + '...' : 'Token hidden'"></span>
                                            </code>
                                        </div>
                                    </div>
                                    <div class="flex gap-2">
                                        <button @click="editUser(index)"
                                                class="px-3 py-1 bg-yellow-500 text-white rounded hover:bg-yellow-600 text-sm">
                                            Edit
                                        </button>
                                        <button @click="confirmDeleteUser(index)"
                                                class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-sm">
                                            Delete
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <!-- Add/Edit User Modal -->
        <div x-show="showModal" 
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             x-transition:leave="transition ease-in duration-200"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0"
             class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
             @click.self="showModal = false">
            <div class="bg-white rounded-lg p-6 max-w-md w-full">
                <h3 class="text-lg font-bold mb-4" x-text="editingIndex === null ? 'Add New User' : 'Edit User'"></h3>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Name</label>
                    <input type="text" x-model="formData.name" 
                           class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-blue-500"
                           placeholder="Enter user name">
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Token</label>
                    <input type="text" x-model="formData.token" 
                           class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-blue-500 font-mono text-sm"
                           placeholder="Enter authentication token">
                    <p class="text-xs text-gray-500 mt-1">This token will be used to authenticate API requests</p>
                </div>
                
                <div class="mt-6 flex gap-2 justify-end">
                    <button @click="showModal = false" 
                            class="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400">
                        Cancel
                    </button>
                    <button @click="saveUser()" 
                            class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
                        <span x-text="editingIndex === null ? 'Add User' : 'Update User'"></span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Delete Confirmation Modal -->
        <div x-show="showDeleteModal" 
             x-transition:enter="transition ease-out duration-300"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             x-transition:leave="transition ease-in duration-200"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0"
             class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
             @click.self="showDeleteModal = false">
            <div class="bg-white rounded-lg p-6 max-w-md w-full">
                <h3 class="text-lg font-bold mb-4 text-red-600">⚠️ Confirm Delete</h3>
                <p class="text-gray-700 mb-2">
                    Are you sure you want to delete user "<strong x-text="deleteUserName"></strong>"?
                </p>
                <p class="text-sm text-gray-500 mb-6">This action cannot be undone.</p>
                <div class="mt-6 flex gap-2 justify-end">
                    <button @click="showDeleteModal = false" 
                            class="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400">
                        Cancel
                    </button>
                    <button @click="deleteUser()" 
                            class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600">
                        Delete User
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        function userManager() {
            return {
                users: [],
                authStatus: {
                    enabled: false,
                    userCount: 0
                },
                loading: false,
                showModal: false,
                showDeleteModal: false,
                editingIndex: null,
                deleteUserIndex: null,
                deleteUserName: '',
                formData: {
                    name: '',
                    token: ''
                },
                alertMessage: '',
                alertType: 'success',

                async init() {
                    console.log('User Manager initializing...');
                    await this.loadUsers();
                    // Auto refresh every 30 seconds
                    setInterval(() => this.loadUsers(true), 30000);
                },

                async loadUsers(silent = false) {
                    if (!silent) this.loading = true;
                    try {
                        // Load users
                        const usersResponse = await fetch('/api/users');
                        const usersData = await usersResponse.json();
                        this.users = usersData;
                        console.log('Loaded ' + this.users.length + ' users');

                        // Load auth status
                        const statusResponse = await fetch('/api/users/status');
                        const statusData = await statusResponse.json();
                        this.authStatus = statusData;
                        console.log('Auth status:', this.authStatus);
                    } catch (error) {
                        console.error('Error loading users:', error);
                        if (!silent) {
                            this.showAlert('Error loading users: ' + error.message, 'error');
                        }
                    } finally {
                        this.loading = false;
                    }
                },

                showAddUserModal() {
                    this.editingIndex = null;
                    this.formData = { name: '', token: '' };
                    this.showModal = true;
                },

                editUser(index) {
                    const user = this.users[index];
                    this.editingIndex = index;
                    this.formData = {
                        name: user.name,
                        token: user.token || ''
                    };
                    this.showModal = true;
                },

                async saveUser() {
                    try {
                        if (!this.formData.name || !this.formData.token) {
                            this.showAlert('Please enter both name and token', 'error');
                            return;
                        }

                        let response;
                        if (this.editingIndex === null) {
                            // Add new user
                            response = await fetch('/api/users', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(this.formData)
                            });
                        } else {
                            // Update existing user
                            response = await fetch(\`/api/users/\${this.editingIndex}\`, {
                                method: 'PUT',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(this.formData)
                            });
                        }

                        const data = await response.json();
                        
                        if (response.ok) {
                            const action = this.editingIndex === null ? 'added' : 'updated';
                            this.showAlert(\`User "\${data.name}" \${action} successfully\`, 'success');
                            this.showModal = false;
                            await this.loadUsers(true);
                        } else {
                            this.showAlert('Error: ' + (data.error || 'Unknown error'), 'error');
                        }
                    } catch (error) {
                        this.showAlert('Error saving user: ' + error.message, 'error');
                    }
                },

                confirmDeleteUser(index) {
                    const user = this.users[index];
                    this.deleteUserIndex = index;
                    this.deleteUserName = user.name;
                    this.showDeleteModal = true;
                },

                async deleteUser() {
                    try {
                        const response = await fetch(\`/api/users/\${this.deleteUserIndex}\`, {
                            method: 'DELETE'
                        });

                        if (response.ok) {
                            this.showAlert(\`User "\${this.deleteUserName}" deleted successfully\`, 'success');
                            this.showDeleteModal = false;
                            await this.loadUsers(true);
                        } else {
                            const data = await response.json();
                            this.showAlert('Error: ' + (data.error || 'Unknown error'), 'error');
                        }
                    } catch (error) {
                        this.showAlert('Error deleting user: ' + error.message, 'error');
                    }
                },

                showAlert(message, type = 'success') {
                    this.alertMessage = message;
                    this.alertType = type;
                    setTimeout(() => {
                        this.alertMessage = '';
                    }, 5000);
                }
            };
        }
    </script>
    <script src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
</body>
</html>`;
}